package servlets.games;

import hibernate.method.AdditionalMethods;
import hibernate.method.GameCategoryMethods;
import hibernate.method.GameMethods;
import hibernate.model.Game;
import hibernate.util.HibernateUtil;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
//import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class AddGame
 */
@WebServlet("/AddGame")
public class AddGame extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddGame() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String name = (String) request.getParameter("name");
		String opis = (String) request.getParameter("opis");
	
		String [] category = request.getParameterValues("categories");		
		String users_min = (String) request.getParameter("users_min");
		String users_max = (String) request.getParameter("users_max");
		InputStream inputStream = null;	// input stream of the upload file
		if(users_min ==null || String.valueOf(users_min).length()==0|| String.valueOf(users_min) =="" ){
			users_min = "0";
		}
		if( users_max == null|| String.valueOf(users_max).length()==0 || String.valueOf(users_max) =="" ){
			users_max = "0";
		}
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		GameMethods gm = new GameMethods();
		GameCategoryMethods gcatm = new GameCategoryMethods();
		System.err.println(opis);
		//gm.addGame(sessionFactory, session, name, opis, Integer.parseInt(users_min),
				//Integer.parseInt(users_max));
		Game g = new Game();
		g.setAdded(AdditionalMethods.getCurrentDate());
		g.setDescribe(opis);
		g.setName(name);
		g.setUsers_max(1);
		g.setUsers_min(1);
		session.save(g);
		
		Integer game_id = gm.nameToId(sessionFactory, session, name);
		if(category != null){
			for(int i=0;i<category.length;i++)
		        gcatm.addCategoryToGame(sessionFactory, session, game_id, Integer.parseInt(category[i]));
			}

		
			
			try {
			String dbURL = "jdbc:mysql://localhost:3306/thesis";
			String dbUser = "root";
			String dbPass = "";

			Connection conn = null;	
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			conn = DriverManager.getConnection(dbURL, dbUser, dbPass);

			Part filePart = request.getPart("avatar");
			if (filePart != null) {
				// prints out some information for debugging
				System.out.println(filePart.getName());
				System.out.println(filePart.getSize());
				System.out.println(filePart.getContentType());
				
				// obtains input stream of the upload file
				inputStream = filePart.getInputStream();
			}
//			
			if (inputStream != null) {
				String sql = "INSERT INTO gamesavatars (game_id, avatar) values (?, ?)";
				PreparedStatement statement = conn.prepareStatement(sql);
				statement.setLong(1, gm.nameToId(sessionFactory, session, name));
				statement.setBlob(2, inputStream);
				statement.executeUpdate();
			}
			if (filePart.getSize()==0) {
				 inputStream = new FileInputStream("M://Thesis/Thesis/src/servlets/games/brak.png");
				String sql = "INSERT INTO gamesavatars (game_id, avatar) values (?, ?)";
				PreparedStatement statement = conn.prepareStatement(sql);
				statement.setLong(1, gm.nameToId(sessionFactory, session, name));
				statement.setBlob(2, inputStream);
				statement.executeUpdate();
			}
			
			session.getTransaction().commit();
			out.println("<script type=\"text/javascript\">alert(\"Gra zostala dodana pomyslnie\"); window.location.href = \"social/index.jsp?page=games&group=newGame\";</script>");
		} catch (Exception e) {
			out.println("<script type=\"text/javascript\">alert(\"Gra nie zostala dodana\"); window.location.href = \"social/index.jsp?page=games&group=newGame\";</script>");
			System.err.println(e.getMessage());
		}
			session.close();

	}

}
